import { Button, Modal } from 'antd';
import { calcInvAgeCheck } from '../../service';
import AgeCalcProgress from '../AgeCalcProgress';

export const getStartAandEndYear = (accountYearData: any[]) => {
  let startYear = '',
    endYear = ''; // 获取当前年度
  if (Array.isArray(accountYearData) && accountYearData.length > 0) {
    startYear = accountYearData[0]['Data_ID'];
    endYear = accountYearData[accountYearData.length - 1]['Data_ID'];
    return {
      startYear,
      endYear,
    };
  }
  return {
    startYear,
    endYear,
  };
};

const AgeCalcButton = (props: any) => {
  const {
    dbname,
    accountYear,
    statisticType,
    calcLoading,
    accountYearData,
    onOK,
    progressInfo,
    startAndEndYear,
  } = props;

  const { startYear, endYear } = getStartAandEndYear(accountYearData);
  const checkNeedCalc = async () => {
    const res = await calcInvAgeCheck({
      dbname,
      Data_ID: accountYear,
      statisticType,
      startYear,
      endYear,
    });
    if (res.success) {
      const data = res?.data || [];
      if (data.length > 0) {
        return true;
      }
    }
  };

  return (
    <>
      <Button
        type="primary"
        size="middle"
        loading={calcLoading}
        className="invAge-setting-btn"
        onClick={async () => {
          checkNeedCalc().then(async (res) => {
            if (res) {
              Modal.confirm({
                title: '提示',
                content: `【${startYear}-${endYear}年度区间】【${statisticType}】库龄已计算完成，是否重新计算，确定吗?`,
                okText: '重新计算',
                cancelText: '取消',
                onOk: async () => {
                  if (onOK) {
                    onOK();
                  }
                },
                onCancel: async () => {
                  // await reCalcInvAge();
                },
              });
            } else {
              Modal.confirm({
                title: '提示',
                content: `【${startYear}-${endYear}年度区间】【${statisticType}】库龄将开始计算，确定吗？`,
                okText: '确定',
                cancelText: '取消',
                onOk: async () => {
                  if (onOK) {
                    onOK();
                  }
                },
              });
            }
          });
        }}
      >
        库龄计算
      </Button>
      <AgeCalcProgress
        title={`【${startAndEndYear.startYear}-${startAndEndYear.endYear}年度区间】【${statisticType}】 库龄计算中`}
        calcLoading={calcLoading}
        progressInfo={progressInfo}
      />
    </>
  );
};

export default AgeCalcButton;
